/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lxq.cloud.ai.controller;


import com.lxq.cloud.ai.entity.AudioResult;
import com.lxq.cloud.ai.service.AudioService;
import com.lxq.cloud.ai.service.ChatService;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
@CrossOrigin
@Slf4j
public class ChatModelController {

    private final ChatModel chatModel;
    private final ChatService chatService;
    private final AudioService audioService;
    public ChatModelController(ChatModel chatModel, ChatService chatService, AudioService audioService) {
        log.info("chatModel: {}", chatModel.getDefaultOptions().getModel());
        this.chatModel = chatModel;
        this.chatService = chatService;
        this.audioService = audioService;
    }

    // 新增私有方法用于统一记录响应日志
    private void logResponse(String content) {
        log.info("response: {}", content);
    }

    @GetMapping("/chat")

    public String chat(@RequestParam(value = "message", defaultValue = "你好，请问有什么可以帮助您？") String message) {
        ChatResponse response = chatModel.call(new Prompt(message));
        String content = response.getResult().getOutput().getText();
        logResponse(content);
        return content;
    }


    @GetMapping("/stream")
    public String stream(String input) {
        StringBuilder res = new StringBuilder();
        Flux<ChatResponse> stream = chatModel.stream(new Prompt(input));
        stream.toStream().toList().forEach(resp -> {
            res.append(resp.getResult().getOutput().getText());
        });
        String content = res.toString();
        logResponse(content);
        return content;
    }


    @GetMapping("/chat2")
    public String completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return chatService.normalCompletion(message);
    }


    @GetMapping("/stream2")
    public Map<String, String> streamCompletion(@RequestParam(value = "message", defaultValue = "请告诉我西红柿炖牛腩怎么做？") String message) {
        return chatService.streamCompletion(message);
    }




    @GetMapping("/audio")
    public ResponseEntity<byte[]> genAudio(@RequestParam(value = "prompt",
            defaultValue = "想不到时间过得这么快！昨天和你视频聊天，看到你那自豪又满意的笑容，我的心里呀，就如同喝了一瓶蜜一样甜呢！真心为你开心呢！") String prompt) {
        AudioResult audioResult = audioService.genAudio(prompt);
        // 构建 HTTP 响应头
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.parseMediaType("audio/mpeg")); // 修改为实际音频类型
        headers.setContentDispositionFormData("inline", audioResult.getFileName()); // 使用 inline 表示浏览器内显示

        return ResponseEntity.ok()
                .headers(headers)
                .body(audioResult.getContent());
    }

}
